#include "port.h"
#include <iconv.h>
#include <assert.h>

// convert UTF-8 string pointed by s into UCS-4 Wide String at pwcs.
size_t MBSTOWCS(TWCHAR *pwcs, const char *s, size_t n) {
  static iconv_t ic = iconv_open("UCS-4LE", "UTF-8");
  assert(ic != (iconv_t)(-1));  // no error allowed!

  TIConvSrcPtr src = (TIConvSrcPtr)s;
  size_t srclen = strlen(s) + 1;
  char *dst = (char *)pwcs;
  size_t dstlen = n*sizeof(TWCHAR);

  size_t res = iconv(ic, &src, &srclen, &dst, &dstlen);

  if (res != size_t(-1) && srclen == 0) {
    n -= dstlen/sizeof(TWCHAR);
    return (n>0)?(n-1):0;
  } else {
    return size_t(-1);
  }
}

// convert UCS-4 string pointed by pwcs into UTF-8 String at s.
size_t WCSTOMBS(char *s, const TWCHAR *pwcs, size_t n)
{
  static iconv_t ic = iconv_open("UTF-8", "UCS-4LE");
  assert(ic != (iconv_t)(-1));

  TIConvSrcPtr src = (TIConvSrcPtr)pwcs;
  size_t srclen = (WCSLEN(pwcs)+1)*sizeof(TWCHAR);
  char *dst = (char *)s;
  size_t dstlen = n;

  size_t res = iconv(ic, &src, &srclen, &dst, &dstlen);

  if (res != size_t(-1) && srclen == 0) {
    n -= dstlen;
    return (n>0)?(n-1):0;
  } else {
    return (size_t)(-1);
  }
}

// return the wide string len at pwcs, not count the end 0.
size_t WCSLEN(const TWCHAR *pwcs)
{
  size_t sz = 0;
  if (pwcs) {
    while (*pwcs++) 
      ++sz;
  }
  return sz;
}

#ifdef TEST 

#include <iostream>
int main()
{
  FILE *fp = NULL;
  FILE *fp2 = NULL;
  static char buf[1024];
  static TWCHAR wword[sizeof(buf)];
  unsigned int id;

  if ((fp2 = fopen("dictConved.utf8", "w")) == NULL)
    return false;
  if ((fp = fopen("dict.utf8", "r")) == NULL)
    return false;
  while (fgets(buf, 1024, fp) != NULL) {
    if (*buf == '\n' || *buf == '#')
      continue;
    char *p = buf;
    while (*p == ' ' || *p == '\t')
      ++p;
    char *pstart = p;
    while (*p != 0 && *p != ' ' && *p != '\t')
      ++p;
    if (*p == 0)
      continue;
    *p++ = 0;
    while (*p == ' ' || *p == '\t')
      ++p;
    if (!(*p >= '0' && *p <= '9'))
      continue;
    for (id = 0; *p >= '0' && *p <= '9'; ++p)
      id = id*10 + (*p-'0');
    if (id < ID_REALWORD_START)
      continue;
    if (MBSTOWCS(wword, pstart, sizeof(buf)) != ((size_t)(-1))) {
      //std::cout << "good" << std::endl;
      fputs(wword, fp2);
    } else {
      fprintf(stderr, "mbs to wcs conversion error for :%s %d \n", buf, id);
    }
  }
  return 0;
}

#endif
